import {
    Message
} from 'element-ui';

export default {
    //全局消息提示框
    showMsg(msg, type) {
        Message({
            message: msg,
            type,
        })
    },
    dateFormat(fmt) {
        let o = {
            "M+": this.getMonth() + 1, //月份 
            "d+": this.getDate(), //日 
            "h+": this.getHours(), //小时 
            "m+": this.getMinutes(), //分 
            "s+": this.getSeconds(), //秒 
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
            "S": this.getMilliseconds() //毫秒 
        };
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (let k in o) {
            if (new RegExp("(" + k + ")").test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }
        return fmt;
    },
    formatTime(time, fmt = 'yyyy-MM-dd hh:mm:ss') {
        if (!time) {
            return
        }
        if (!(time instanceof Date)) {
            try {
                time = new Date(time)
            } catch {
                console.log('格式不正确')
            }
        }
        let o = {
            "M+": time.getMonth() + 1, //月份 
            "d+": time.getDate(), //日 
            "h+": time.getHours(), //小时 
            "m+": time.getMinutes(), //分 
            "s+": time.getSeconds(), //秒 
            "q+": Math.floor((time.getMonth() + 3) / 3), //季度 
            "S": time.getMilliseconds() //毫秒 
        };
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (time.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (let k in o) {
            if (new RegExp("(" + k + ")").test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }
        return fmt;
    },
    subString(value, start = 0, end) {
        if (!value) return '';
        let len = value.length
        end = end || len
        return len > end ? value.substring(start, end) + '...' : value
    },
    //计算页数
    countPage(count, pageSize) {
        if (count > 0) {
            let pageCount = count % pageSize == 0 ? count / pageSize : count / pageSize + 1
            let c = pageCount.toFixed(0)
            pageCount = c > pageCount ? c - 1 : c
            return pageCount
        } else {
            return 0
        }
    },
    //拼接字符串 处理树结构回显名称
    handleNames(userNames, depNames) {
        let namesArr = []
        let tempUserNames = []
        let tempDepNames = []
        tempUserNames = this.handleString(userNames)
        tempDepNames = this.handleString(depNames)
        namesArr = [...tempUserNames, ...tempDepNames].toString()
        return namesArr
    },
    handleString(names) {
        return names === null ? [] : names.split(',')
    },
    //过滤自定义字段
    filterCustomFields(fieldList) {
        return fieldList.filter(i => !(!isNaN(parseFloat(i.label)) && isFinite(i.label)))
    },
    //表格不在第一页时，删除最后一行数据时，要返回到上一页的数据
    countTableDelLastLinePage(total, page, limit) {
        let totalPage = Math.ceil((total - 1) / limit)
        let currentPage = page > totalPage ? totalPage : page
        return currentPage < 1 ? 1 : currentPage
    },
    toChineseNumber(num) {
        const strs = num
            .toString()
            .replace(/(?=(\d{4})+s)/g, ',')
            .split(',')
            .filter(Boolean)
        const chars = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
        const units = ['', '十', '百', '千']
        const bigUnits = ['', '万', '亿']
        const map = {
            零: '零',
            一: '壹',
            二: '贰',
            三: '叁',
            四: '肆',
            五: '伍',
            六: '陆',
            七: '柒',
            八: '捌',
            九: '玖',
            十: '拾',
            百: '佰',
            千: '仟',
            万: '萬',
            亿: '亿',
        }

        function _transform(numStr) {
            let result = ''
            for (let i = 0; i < numStr.length; i++) {
                const digit = +numStr[i]
                const c = chars[digit]
                const u = units[numStr.length - 1 - i]
                if (digit === 0) {
                    if (result[result.length - 1] !== chars[0]) {
                        result += c
                    }
                } else {
                    result += c + u
                }
            }
            if (result[result.length - 1] !== chars[0]) {
                result = result.slice(0, -1)
            }
            return result
        }
        let result = ''
        for (let i = 0; i < strs.length; i++) {
            const part = strs[i]
            const c = _transform(part)
            const u = c ? bigUnits[strs.length - 1 - i] : ''
            result += c + u
        }
        return result.split('').map(s => map[s]).join('')
    },
    digitUppercase(n) {
        var fraction = ['角', '分'];
        var digit = [
            '零', '壹', '贰', '叁', '肆',
            '伍', '陆', '柒', '捌', '玖'
        ];
        var unit = [
            ['元', '万', '亿'],
            ['', '拾', '佰', '仟']
        ];
        var head = n < 0 ? '欠' : '';
        n = Math.abs(n);
        var s = '';
        for (var i = 0; i < fraction.length; i++) {
            s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
        }
        s = s || '整';
        n = Math.floor(n);
        for (var i = 0; i < unit[0].length && n > 0; i++) {
            var p = '';
            for (var j = 0; j < unit[1].length && n > 0; j++) {
                p = digit[n % 10] + unit[1][j] + p;
                n = Math.floor(n / 10);
            }
            s = p.replace(/(零.)*零$/, '')
                .replace(/^$/, '零') + unit[0][i] + s;
        }
        return head + s.replace(/(零.)*零元/, '元')
            .replace(/(零.)+/g, '零')
            .replace(/^整$/, '零元整');
    },
    //创建一个防抖函数debounce
    debounce(fn, delay, immediate = false) {
        // 1.定义一个定时器, 保存上一次的定时器
        let timer = null
        let isInvoke = false
        // 2.真正执行的函数
        const _debounce = function (...ages) {
            // 取消上一次的定时器
            if (timer) clearTimeout(timer)

            // 判断是否需要立即执行
            if (immediate && !isInvoke) {
                fn.apply(this, ages)
                isInvoke = true
            } else {
                // 延迟执行
                timer = setTimeout(() => {
                    // 外部传入的真正要执行的函数
                    fn.apply(this, ages)
                    isInvoke = false
                }, delay)
            }
        }
        return _debounce
    }

}